package com.device.common.interceptor;

import com.device.entity.User;
import com.device.util.DesUtil;
import lombok.extern.slf4j.Slf4j;
import com.device.util.CookieUtil;
import com.alibaba.fastjson.JSONObject;
import com.device.util.PltThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * @author lyn
 * @date 2017年4月11日
 * @说明: 后台拦截器
 **/
@Slf4j
public class LoginInterceptor extends HandlerInterceptorAdapter{
	
	@Override
	public boolean preHandle(HttpServletRequest request, 
			HttpServletResponse response,Object handler) throws Exception {
		String url = request.getRequestURI();
		log.info("admin=="+url);
		String value = CookieUtil.getValue(request,"adminInfo");
		if(StringUtils.isNotEmpty(value)){
			String infovalue = DesUtil.decrypt(value);
			JSONObject loginInfo = JSONObject.parseObject(infovalue);
			User user = JSONObject.toJavaObject(loginInfo,User.class);
			PltThreadLocalUtil.setUser(user);
			return true;
		}else{
			String base=request.getScheme()+"://"+request.getServerName()+
					":"+request.getServerPort()+request.getContextPath()+"/"; 
			response.sendRedirect(base+"admin/login");
			return false;
		}
	}
}